<template>
  <list
      v-model="searchParams"
      :headers="headers"
      isHasOperateColumn
      isMultiSelect
      :searchUrl="data.searchUrl"
      ref="listRef"
      :operateColumnWidth="300"
  >
    <template #operateBtnsSlot="{ selectData }">
      <v-button type="primary" @click="addUser" v-permission="`btn.User.add`" text="新增用户"/>
      <v-button
          type="danger"
          :disabled="!Boolean(selectData.data.length)"
          @click="batchDelete(selectData)"
          text="批量删除"
          v-permission="`btn.User.remove`"
      />
    </template>
    <template #operateSlot="scope">
      <v-button @click="assignRole(scope.row)" text="分配角色" v-permission="`btn.User.assign`"/>
      <v-button type="danger" @click="deleteHandle(scope.row)" text="删除"
                v-permission="`btn.User.remove`"/>
      <v-button type="primary" text="编辑" v-permission="`btn.User.update`" @click="editUser(scope.row)"/>
    </template>
    <template #searchSlot>
      <v-input label="账号" v-model="searchParams.username"/>
      <v-input label="角色" v-model="searchParams.roleName"/>
      <v-date-picker label="创建时间" v-model:startTime="searchParams.startTime" v-model:endTime="searchParams.endTime"
                     :width="300"/>
    </template>
  </list>
  <el-drawer
      v-model="data.isShowDrawer"
      title="分配角色"
      direction="rtl"
      :before-close="handleClose"
  >
    <div>
      <el-form>
        <el-form-item>
          <v-input :disabled="true" v-model="data.currentUserName" label="用户姓名"/>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox v-model="data.checkAll" :indeterminate="data.indeterminate" @change="handleCheckAllChange"
                       style="width: 100%">全选
          </el-checkbox>
          <el-checkbox-group v-model="data.roleId" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in data.allRolesList" :key="item.id" :label="item.id">{{ item.jobTitle }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <v-button @click="()=>data.isShowDrawer=false" text="取消"/>
      <v-button type="primary" @click="saveRole" text="确定"/>
    </template>
  </el-drawer>
</template>
<script lang="tsx" setup>
import {reactive, ref, watch, inject, h} from 'vue'
import router from "@/router";
import {
  getUserRoleDetailApi,
  saveUserRoleApi,
  deleteUserApi,
  updateUserStatusApi,
  batchDeleteUserApi
} from "@/api/user";
import {ElSwitch} from "element-plus";

let $messageBox: any = inject('$messageBox')
let $message: any = inject('$message')

let searchParams = ref({
  username: '',
  roleName: '',
  endTime: '',
  startTime: ''
})
const listRef = ref()
const headers = reactive<TableHeader[]>([
  {
    prop: 'username',
    label: '账号'
  },
  {
    prop: 'nickname',
    label: '姓名'
  },
  {
    prop: 'roleName',
    label: '用户角色'
  },
  {
    prop: 'status',
    label: '用户状态',
    render: (row) => {
      return h(ElSwitch, {
        modelValue: row.status,
        onChange: (status: boolean) => {
          updateUserStatusApi(row.id, status).then(res => {
            if (res.status === 0) {
              listRef.value.searchData()
              $message.success(res.msg)
            } else {
              $message.error(res.msg)
            }
          })
        }
      })
    }
  },
  {
    prop: 'createdTime',
    label: '创建时间'
  },
  {
    prop: 'updatedTime',
    label: '更新时间'
  }
])
const data = reactive({
  searchUrl: '/user/list',
  isShowDrawer: false,
  currentUserId: 0,
  currentUserName: '',
  roleId: [],
  allRolesList: [],
  checkAll: false,
  indeterminate: true
})

watch(() => data.isShowDrawer, async (value) => {
  if (value) {
    const res = await getUserRoleDetailApi(data.currentUserId)
    if (res.status === 0) {
      data.allRolesList = res.data.allRolesList;
      data.roleId = res.data.assignRoleIds;
    }
  }
})
const deleteHandle = (row: any) => {
  $messageBox.confirm(
      `确定删除${row.username}吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteUserApi(row.id).then(res => {
      if (res.status === 0) {
        $message.success(res.msg)
        listRef.value.searchData()
      } else {
        $message.error(res.msg)
      }
    })
  })
}
const editUser = (row) => {
  router.push({
    path: '/permission/editUser',
    query: {
      id: row.id
    }
  })
}

const assignRole = (row) => {
  data.currentUserId = row.id;
  data.isShowDrawer = true;
  data.currentUserName = row.nickname
}

const batchDelete = (scope: any) => {
  const data = scope.ids.join(',')
  $messageBox.confirm(
      `确定删除这些用户吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    batchDeleteUserApi(data).then(res => {
      if (res.status === 0) {
        $message.success('删除成功')
        listRef.value.searchData()
      } else {
        $message.error('删除失败')
      }
    })
  })
}

const saveRole = async () => {
  if (data.roleId.length > 0) {
    const res = await saveUserRoleApi({userId: data.currentUserId, roleId: data.roleId.join(',')})
    if (res.status === 0) {
      data.isShowDrawer = false
      listRef.value.searchData()
    }else {
      $message.warning(res.msg)
    }
  } else {
    $message.warning('请选择角色')
  }

}

const handleCheckAllChange = (val: boolean) => {
  data.roleId = val ? data.allRolesList.map(item => item.id) : []
  data.indeterminate = false
}

const handleClose = (done: () => void) => {
  done()
}

const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  data.checkAll = checkedCount === data.roleId.length && checkedCount > 0
  data.indeterminate = checkedCount > 0 && checkedCount < data.allRolesList.length
}

const addUser = () => {
  router.push('/permission/addUser')
}

</script>
<style scoped lang="scss"></style>
